package com.remoting.api.request.support;

import com.remoting.api.registry.bean.HostInfo;
import com.remoting.api.registry.bean.ServiceImportInfo;
import com.remoting.api.request.RequestHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Map.Entry;


/**
 * get请求参数
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2018年12月27日下午1:37:14
 */
public class GetRequest extends RemoteRequest{
	
	public GetRequest(RequestHandler requestHandler, ServiceImportInfo serviceImportInfo, Map<String, Object> params) {
		super(requestHandler,serviceImportInfo,params);
	}
	public GetRequest doBuilder(HostInfo host){
		String address = populateGetAddress(host);
		this.setAddress(address);
		return this;
	}
	/**
	 * 组装GET请求URL
	 * <p>说明:</p>
	 * <li></li>
	 * @author DuanYong
	 * @param host 主机信息
	 * @return  GET请求URL
	 * @since 2018年12月27日下午4:26:16
	 */
	private String populateGetAddress(HostInfo host) {
		//组装请求地址
		StringBuilder address = new StringBuilder();
		address.append(this.getServiceImportInfo().getEndpoint().getType()).append(":").append(host.toUrl())
				.append(this.getServiceImportInfo().getEndpoint().getServiceAddr()).append(this.getServiceImportInfo().getApi());
		StringBuilder url = new StringBuilder();
		//组装URL请求地址中的参数
		if (null != this.getServiceImportInfo().getParams() && !this.getServiceImportInfo().getParams().isEmpty()) {
			String value = "";
			for (Entry<String,String> entry :  this.getServiceImportInfo().getParams().entrySet()) {
				value = entry.getValue();
				if (StringUtils.isBlank(value)) {
					continue;
				}
				value = this.getRequestHandler().parserValue(this.getServiceImportInfo(), host, this.getParams(), value);
				url.append(entry.getKey()).append("=").append(value).append("&");
			}
		}
		//请求参数不为空，则将参数组装到URL后面
		if (!this.getParams().isEmpty()) {
			for (Entry<String,Object> entry : this.getParams().entrySet()) {
				if (null == entry.getValue()) {
					continue;
				}
				url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}
		if (StringUtils.isNotBlank(url.toString())) {
			address.append("?").append(url.toString().substring(0, url.length() - 1));
		}
		return address.toString();
	}
	

}
